package com.example.fmgidsprototype;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.ImageView;

public class ImageDownloader extends AsyncTask<String, Void, Drawable>{
	
	private ImageView imgView;
	
	public ImageDownloader(ImageView imgView){
		this.imgView = imgView;
	}

	@Override
	protected Drawable doInBackground(String... args) {
		String url = args[0];
		return this.loadFromUrl(url);
	}
	
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
	}
	
	protected void onPostExecute(Drawable result){
		this.imgView.setImageDrawable(result);
	}
	
	private Drawable loadFromUrl(String url){
		Drawable drawable = null;
		try{
			URL myUrl = new URL(url);
			URLConnection conn = myUrl.openConnection();
			conn.setConnectTimeout(3000);
	        conn.setReadTimeout(5000);
	        drawable = Drawable.createFromStream(conn.getInputStream(), "src");
		}
		catch(MalformedURLException me){
			me.printStackTrace();
		}
		catch(IOException ioe){
			ioe.printStackTrace();
		}
		
		return drawable;
	}

}
